package com.neusoft.admin.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import com.neusoft.admin.method.AlertUtils;
import com.neusoft.admin.method.GetColor;
import com.neusoft.admin.entity.feedbackData;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class feedbackListViewControl implements Initializable {
    @FXML
    private TableView<feedbackData> feedbackTableView;
    @FXML
    private TableColumn<feedbackData, String> idColumn, nameColumn, dateColumn, timeColumn, gradeColumn, provinceColumn,
            cityColumn;
    @FXML
    private TableColumn<feedbackData, Void> contentColumn, actionColumn;
    @FXML
    private ComboBox<String> provinceComboBox, cityComboBox, gradeComboBox;
    @FXML
    private ObservableList<feedbackData> feedbackDataList = FXCollections.observableArrayList();
    @FXML
    private Button clearButton;
    @FXML
    private RadioButton assignedRadioButton, unassignedRadioButton;
    @FXML
    private ToggleGroup tg;
    @FXML
    private DatePicker datePicker;
    private String ComboBoxStyle = "-fx-background-color: transparent; -fx-border-color:#DEE1E8; -fx-border-width: 1px; -fx-border-radius: 5px;";
    private String feedbackId, feedbackerName, feedbackerContact, feedbackProvince, feedbackCity, feedbackLevel,
            feedbackDescription, feedbackDate, feedbackTime, feedbackAssign;
    private Map<String, feedbackData> map = new HashMap<>();
    private feedbackData fData;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setComboBox();
        setToggleGroup();
        clearComboBox();
        read();

        idColumn.setSortable(false);
        nameColumn.setSortable(false);
        dateColumn.setSortable(false);
        timeColumn.setSortable(false);
        gradeColumn.setSortable(false);
        provinceColumn.setSortable(false);
        cityColumn.setSortable(false);
        contentColumn.setSortable(false);
        actionColumn.setSortable(false);
        // 绑定列与属性
        setupColumn(idColumn, "id");
        setupColumn(nameColumn, "name");
        setupColumn(dateColumn, "date");
        setupColumn(timeColumn, "time");
        setGrade(gradeColumn, "grade");
        setupColumn(provinceColumn, "province");
        setupColumn(cityColumn, "city");
        // 将数据设置到 TableView 中
        feedbackTableView.setItems(feedbackDataList);
        // 设置内容列的单元格工厂
        contentColumn.setCellFactory(cols -> new TableCell<>() {
            private Button btn = new Button("查看内容");
            {
                btn.setStyle("-fx-background-color: #3d90fd; -fx-text-fill: white;-fx-background-radius: 5px;");
                btn.setOnAction(_ -> {
                    feedbackData data = getTableView().getItems().get(getIndex());
                    System.out.println("查看内容: " + data.getId());
                    try {
                        Stage stage = new Stage();
                        stage.setTitle("反馈内容查看");
                        // 加载 FXML 文件
                        FXMLLoader loader = new FXMLLoader(
                                getClass().getResource("/com/neusoft/admin/view/feedbackView.fxml"));
                        // 创建控制器实例并传入参数
                        feedbackViewControl controller = new feedbackViewControl(data.getId());
                        // 设置控制器
                        loader.setController(controller);
                        // 加载 FXML 内容
                        Parent root = loader.load();
                        stage.setScene(new Scene(root));
                        stage.show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setAlignment(Pos.CENTER); // 设置按钮居中对齐
                // 根据单元格是否为空设置显示的图形，空则不显示按钮
                setGraphic(empty ? null : btn);
            }
        });
        actionColumn.setCellFactory(cols -> new TableCell<>() {
            private Button btn = new Button("处理");
            {
                btn.setStyle("-fx-background-color: #F56C6C; -fx-text-fill: white;-fx-background-radius: 5px;");
                btn.setOnAction(_ -> {

                    feedbackData data = getTableView().getItems().get(getIndex());

                    System.out.println("处理反馈: " + data.getId());
                    try {
                        if (map.get(data.getId()).getAssigned().equals("未指派")) {
                            Stage stage = new Stage();
                            stage.setTitle("反馈内容查看");
                            // 加载 FXML 文件
                            FXMLLoader loader = new FXMLLoader(
                                    getClass().getResource("/com/neusoft/admin/view/feedbackAssignView.fxml"));
                            // 创建控制器实例并传入参数
                            feedbackAssignViewControl controller = new feedbackAssignViewControl(data.getId());
                            // 设置控制器
                            loader.setController(controller);
                            // 加载 FXML 内容
                            Parent root = loader.load();
                            stage.setScene(new Scene(root));
                            stage.show();
                            // 监听窗口关闭事件，在窗口关闭后刷新列表
                            stage.setOnHidden(event -> {
                                clearTableView();
                                handleSearch(); // 调用搜索方法刷新列表
                            });
                        } else {
                            AlertUtils.showDialog("提示", "该反馈已指派，不能重复指派！");
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setAlignment(Pos.CENTER); // 设置按钮居中对齐
                // 根据单元格是否为空设置显示的图形，空则不显示按钮
                setGraphic(empty ? null : btn);
            }

        });
    }
    public void clearTableView() {
        // 清空数据源
        feedbackDataList.clear();
        read();
        // 刷新 TableView
        feedbackTableView.refresh();
    }
    public void setToggleGroup() {
        tg = new ToggleGroup();
        assignedRadioButton.setToggleGroup(tg);
        unassignedRadioButton.setToggleGroup(tg);
        tg.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                System.out.println("选择的处理状态: " + ((RadioButton) newValue).getText());
                handleSearch();
            }
        });
    }

    public void read() {
        File file = new File("src/com/neusoft/admin/data/mission.txt");
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            if (!file.exists()) {
                System.out.println("文件不存在");
                return;
            }
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(" ");
                feedbackId =parts[0];
                feedbackerName = parts[2];
                feedbackProvince = parts[6];
                feedbackCity = parts[7];
                feedbackLevel = parts[11];
                feedbackDescription = parts[13];
                int yearIndex=parts[15].indexOf("年");
                int monthIndex=parts[15].indexOf("月");
                int dayIndex=parts[15].indexOf("日");

                String yearValue = parts[15].substring(0,yearIndex);
                int monthValue = Integer.parseInt(parts[15].substring(yearIndex+1,monthIndex));
                int dayValue = Integer.parseInt(parts[15].substring(monthIndex+1,dayIndex));
                if (monthValue < 10) {
                    feedbackDate = yearValue + "-0" + monthValue + "-";
                    if (dayValue < 10) {
                        feedbackDate += "0" + dayValue;
                    } else {
                        feedbackDate += dayValue;
                    }

                } else {
                    feedbackDate = yearValue + "-" + monthValue + "-";
                    if (dayValue < 10) {
                        feedbackDate += "0" + dayValue;
                    } else {
                        feedbackDate += dayValue;
                    }
                }
                feedbackTime = "";
                feedbackAssign = parts[16];
                fData = new feedbackData(feedbackId, feedbackerName, feedbackProvince, feedbackCity,
                        feedbackLevel, feedbackDate, feedbackTime, feedbackAssign);
                map.put(feedbackId, fData);
                System.out.println(fData.getCity());
            }
            feedbackDataList.addAll(map.values());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setComboBox() {
        ObservableList<String> provinceData = FXCollections.observableArrayList("全部", "北京市", "辽宁省", "广东");
        provinceComboBox.setItems(provinceData);
        provinceComboBox.setStyle(ComboBoxStyle);
        // 填充市区域数据
        ObservableList<String> cityData = FXCollections.observableArrayList("请选择省区域");
        cityComboBox.setItems(cityData);
        cityComboBox.setStyle(ComboBoxStyle);
        // 填充预估等级数据
        ObservableList<String> gradeData = FXCollections.observableArrayList("全部", "优(一)", "良(二)", "轻度污染(三)", "中度污染(四)",
                "重度污染(五)", "严重污染(六)");
        gradeComboBox.setItems(gradeData);
        gradeComboBox.setStyle(ComboBoxStyle);
        // 为省区域ComboBox添加选择事件处理
        provinceComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                System.out.println("选择的省区域: " + newValue);
                // 根据选择的省区域更新市区域ComboBox的内容
                if ("广东".equals(newValue)) {
                    cityComboBox.setItems(FXCollections.observableArrayList("全部", "广州", "深圳", "珠海"));
                } else if ("北京市".equals(newValue)) {
                    cityComboBox.setItems(FXCollections.observableArrayList("全部", "北京市"));
                } else if ("辽宁省".equals(newValue)) {
                    cityComboBox.setItems(FXCollections.observableArrayList("全部", "沈阳市", "大连市"));
                }
                handleSearch();
            }
        });
        // 为市区域ComboBox添加选择事件处理
        cityComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                System.out.println("选择的市区域: " + newValue);
                handleSearch();
            }
        });
        // 为预估等级ComboBox添加选择事件处理
        gradeComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                System.out.println("选择的预估等级: " + newValue);
                handleSearch();
            }
        });
        datePicker.setStyle(ComboBoxStyle);
        // 设置日期选择器的事件处理
        datePicker.setOnAction(event -> {
            handleSearch();
        });
    }

    public void clearComboBox() {
        // 为清空筛选按钮添加事件处理
        clearButton.setOnAction(event -> {
            provinceComboBox.getSelectionModel().clearSelection();
            cityComboBox.getSelectionModel().clearSelection();
            gradeComboBox.getSelectionModel().clearSelection();
            datePicker.setValue(null);
            tg.selectToggle(null);
            handleSearch();
        });
    }

    public void handleSearch() {
        // 获取用户选择的筛选条件
        String selectedProvince = provinceComboBox.getValue();
        String selectedCity = cityComboBox.getValue();
        String selectedGrade = gradeComboBox.getValue();
        String selectedDate = datePicker.getValue() != null ? datePicker.getValue().toString() : null;
        boolean isAssigned = assignedRadioButton.isSelected();
        boolean isUnassigned = unassignedRadioButton.isSelected();
        // 创建一个新的列表来存储筛选后的数据
        ObservableList<feedbackData> filteredList = FXCollections.observableArrayList();
        Map<String, String> gradeMap = new HashMap<>();
        gradeMap.put("优(一)", "一级");
        gradeMap.put("良(二)", "二级");
        gradeMap.put("轻度污染(三)", "三级");
        gradeMap.put("中度污染(四)", "四级");
        gradeMap.put("重度污染(五)", "五级");
        gradeMap.put("严重污染(六)", "六级");
        // 遍历原始数据列表
        for (feedbackData data : feedbackDataList) {
            boolean matchProvince = true;
            boolean matchCity = true;
            boolean matchGrade = true;
            boolean matchDate = true;
            boolean matchAssigned = true;
            // 检查日期条件
            if (selectedDate != null && !selectedDate.isEmpty() && !selectedDate.equals("全部")) {
                matchDate = data.getDate().equals(selectedDate);
            } else {
                matchDate = true; // 如果没有选择日期，则不进行筛选
            }
            // 检查省份条件
            if (selectedProvince != null && !selectedProvince.isEmpty() && !selectedProvince.equals("全部")) {
                matchProvince = data.getProvince().equals(selectedProvince);
            }

            // 检查城市条件
            if (selectedCity != null && !selectedCity.isEmpty() && !selectedCity.equals("请选择省区域")
                    && !selectedCity.equals("全部")) {
                matchCity = data.getCity().equals(selectedCity);
            }

            // 检查等级条件
            if (selectedGrade != null && !selectedGrade.isEmpty() && !selectedGrade.equals("全部")) {
                boolean matchGrade1 = data.getGrade().equals(selectedGrade);
                String grade = gradeMap.get(selectedGrade);
                boolean matchGrade2 = data.getGrade().equals(grade);
                matchGrade = matchGrade1 || matchGrade2;
            }
            // 检查是否已分配条件
            if (isAssigned) {
                matchAssigned = data.getAssigned().equals("已指派");
                System.out.println("已分配条件匹配: " + matchAssigned);
            } else if (isUnassigned) {
                matchAssigned = data.getAssigned().equals("未指派");
                System.out.println("未分配条件匹配: " + matchAssigned);
            }
            // 如果所有条件都匹配，则将数据添加到筛选列表中
            if (matchProvince && matchCity && matchGrade && matchDate && matchAssigned) {
                filteredList.add(data);
            }
        }

        // 将筛选后的数据设置到 TableView 中
        feedbackTableView.setItems(filteredList);
        feedbackTableView.refresh();
        // 打印搜索条件
        System.out.println("搜索条件: 省区域=" + selectedProvince + ", 市区域=" + selectedCity + ", 预估等级=" + selectedGrade
                + ", 日期=" + selectedDate);
    }

    private <T> void setupColumn(TableColumn<feedbackData, T> column, String property) {
        column.setCellValueFactory(new PropertyValueFactory<>(property));
        column.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(T item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(item.toString());
                }
                // 设置单元格内容居中显示
                setAlignment(Pos.CENTER);
            }
        });
    }

    public void setGrade(TableColumn<feedbackData, String> column, String property) {
        column.setCellValueFactory(new PropertyValueFactory<>(property));
        column.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(String grade, boolean empty) {
                super.updateItem(grade, empty);
                if (empty || grade == null) {
                    setText(null);
                    setStyle("");
                } else {
                    setText(grade);
                    setAlignment(Pos.CENTER);
                    // 根据等级设置背景颜色
                    String gradeColor = GetColor.getColor(grade);
                    setStyle(gradeColor);
                }
            }
        });
    }
}
